package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.ReceptionAddrAdapter;
import com.wnhz.work.yz.bean.AddressBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReceptionAddressActivity extends BaseActivity implements View.OnClickListener {
    private TextView title;
    private TextView tv_right;
    private SwipeMenuListView my_listView;

    private List<AddressBean> addrList = new ArrayList<>();
    private ReceptionAddrAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reception_address);
        initData();
        initView();
    }

    private void initData() {

    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("收货地址");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.submit).setOnClickListener(this);

        tv_right = (TextView) findViewById(R.id.submit);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("新增");
        tv_right.setTextColor(0xff008c99);

        my_listView = (SwipeMenuListView) findViewById(R.id.my_listView);
        updown();
        mAdapter = new ReceptionAddrAdapter(this, addrList);
        my_listView.setAdapter(mAdapter);
        SwipeMenuCreator creater = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {


                //同理create删除item
                SwipeMenuItem deleteItem = new SwipeMenuItem(ReceptionAddressActivity.this);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set item title
                deleteItem.setTitle("删除");
                // set item title fontsize
                deleteItem.setTitleSize(18);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
//                // set a icon
//                deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        my_listView.setMenuCreator(creater);
        my_listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {

                    case 0:
                        //删除的逻辑
                        showDialogv7("确定删除该地址吗？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updelete(position);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
                        break;

                    default:
                        break;
                }
                return false;
            }
        });
        my_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ReceptionAddressActivity.this, AddAddressActivity.class);
                String province = addrList.get(position).getProvince();
                String city = addrList.get(position).getCity();
                String district = addrList.get(position).getDistrict();
                String place = addrList.get(position).getPlace();
                intent.putExtra("title", "修改地址");
                intent.putExtra("name", addrList.get(position).getConsignee());
                intent.putExtra("phone", addrList.get(position).getTelephone());
                intent.putExtra("province", province);
                intent.putExtra("city", city);
                intent.putExtra("district", district);
                intent.putExtra("place", place);
                intent.putExtra("addressId", addrList.get(position).getAddress_id());
                if (position == 0) {
                    intent.putExtra("def", "1");
                }
                startActivity(intent);
            }
        });

        my_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final int s = position;
                showDialogv7("确定删除该地址吗？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        updelete(s);
                    }
                });

                return false;
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    private void updelete(int position) {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("addressId", addrList.get(position).getAddress_id());
        XUtil.Post(Url.MEMBER_DELADDRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                System.out.println("pppppppppppppppp  " + result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(ReceptionAddressActivity.this, LoginNewActivity.class));
//                        return;
//                    }
                    if ("1".equals(res)) {
                        MyToast(info);
                        updown();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private static final String TAG = "ReceptionAddressActivity";

    private void updown() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        XUtil.Post(Url.MEMBER_GETADDRESSLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                System.out.println("address= " + result);
                try {
                    addrList.clear();
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    JSONArray jsonArray = jsonObject.optJSONArray("info");
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            AddressBean bean = new AddressBean();
                            Gson gson = new Gson();
                            bean = gson.fromJson(jsonArray.optString(i), AddressBean.class);

                            addrList.add(bean);
                        }
                        for (int i = 0; i < addrList.size(); i++) {
                            if ("1".equals(addrList.get(i).getDef())) {
                                AddressBean bean = addrList.get(i);
                                addrList.add(0, bean);
                                addrList.remove(i);
                                break;

                            }
                        }
                        for (AddressBean addressBean : addrList) {
                            System.out.println("aaaaaaaaaaaaa     " + addressBean.toString());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        Integer index;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //新增
            case R.id.submit:
                intent = new Intent(this, AddAddressActivity.class);
                intent.putExtra("title", "新增地址");
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        updown();
    }

    @Override
    protected void onResume() {
        updown();
        super.onResume();
    }
}
